package com.dongqi.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * ClassName: StringUtils
 * </p>
 * <p>
 * Description: String处理工具类
 * </p>
 * <p>
 * Author: colick
 * </p>
 * <p>
 * Date: 2015-05-15
 * </p>
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    private static Log log = LogFactory.getLog(StringUtils.class);

    public static final String[] chartSetArray = {
            "utf-8" , "gbk" , "gb2312" , "iso-8859-1"
    };

    public static final String BLANK = "";

    public static final String DEFAULT_CHARSET = "utf-8";

    public static final String DOT = ".";

    public static String firstCharUpperCase(String src) {
        if (Character.isUpperCase(src.charAt(0)))
            return src;
        else {
            StringBuilder sb = new StringBuilder();
            sb.append(Character.toUpperCase(src.charAt(0))).append(
                    src.substring(1));
            return sb.toString();
        }
    }

    public static String[] match(String src, String reg) {
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(src);
        List<String> l = new ArrayList<String>();
        while (m.find()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                l.add(m.group(i));
            }
        }
        return l.toArray(new String[]{});
    }

    public static String matchGroup(String src, String reg, int index) {
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(src);
//		List<String> l = new ArrayList<String>();
        while (m.find()) {
            return m.group(index);
        }
        return BLANK;
    }

    public static String[] matchAll(String src, String reg) {
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(src);
        List<String> l = new ArrayList<String>();
        while (m.find()) {
            l.add(m.group());
        }
        return l.toArray(new String[]{});
    }

    public static String stringtify(Reader in) {
        try {
            StringBuilder sb = new StringBuilder();
            String line = null;
            BufferedReader br = new BufferedReader(in);
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    public static String stringtify(InputStream in) {
        return stringtify(in, DEFAULT_CHARSET);
    }

    public static String stringtify(InputStream in, String charset) {
        try {
            InputStreamReader isr = new InputStreamReader(in, charset);
            return stringtify(isr);
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    /**
     * 字符串前补零
     *
     * @param src       源
     * @param padLength 字符格式化位数
     * @return 返回补零后的结果
     */
    public static String lpad(String src, Integer padLength) {
        int length = padLength - src.length();
        for (int i = 0; i < length; i++) {
            src = "0" + src;
        }
        return src;
    }

    /**
     * 比较是否含有给定字符串
     *
     * @param src 源
     * @param reg 正则
     * @return
     */
    public static boolean matches(String src, String reg) {
        return Pattern.compile(reg).matcher(src).find();
    }

    /**
     * 过滤字符串中的换行符和制表符
     *
     * @param str
     * @return
     */
//    public static String replaceBlank(String str) {
//        String dest = BLANK;
//        if (Utils.notNull(str)) {
//            Pattern p = Pattern.compile("\t|\r|\n");
//            Matcher m = p.matcher(str);
//            dest = m.replaceAll(BLANK);
//        }
//        return dest;
//    }

    public static boolean isBlank(String str) {
        int strLen;
        if(str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if(!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    //随机生成6位验证码
    public static String genRandomPsd(int length) {
        Random rad=new Random();
        String result  = rad.nextInt(1000000) +"";
        if(result.length()!=length){
            return genRandomPsd(length);
        }
        return result;
    }

    public static String valueOf(Object obj) {
        if (obj != null) {
            return obj.toString();
        }
        return "";
    }

    public static boolean isEmpty(Object str) {
        if (str == null || valueOf(str).length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 截取一定长度，后补字符串...
     * @param str
     * @param len
     * @param elide
     * @return
     */
    public static String splitString(String str, int len, String elide) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(str)) {
            return "";
        }

        str = str.replaceAll("<br>", " ");
        str = str.replaceAll("<br/>", " ");
        str = str.replaceAll("<br />", " ");
        str = str.replaceAll("<BR>", " ");
        str = str.replaceAll("<BR/>", " ");
        str = str.replaceAll("<BR />", " ");
        str = str.replaceAll("\n", " ");
        str = str.replaceAll("\r", " ");

        byte[] strByte;
        String resultStr = "";
        try {
            strByte = str.getBytes("UTF-8");
            int strLen = strByte.length;
            if (len >= strLen || len < 1) {
                return str;
            }

            int count = 0;
            for (int i = 0; i < len; i++) {
                int value = (int) strByte[i];
                if (value < 0) {
                    count++;
                }
            }
            if (count % 3 == 1) {
                len = (len > 1) ? (len - 1) : 0;
            } else if (count % 3 == 2) {
                len = (len > 2) ? (len - 2) : 0;
            }

            resultStr = new String(strByte, 0, len, "UTF-8") + elide.trim();
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(),e);
        }

        return resultStr;
    }


    /**
     * 屏蔽使用HTML标签
     * @param str
     * @return
     */
    public static String safeHTML(String str){
        if (org.apache.commons.lang3.StringUtils.isEmpty(str)) {
            return "";
        }

        str = str.replaceAll("&", "&amp;");
        str = str.replaceAll(">", "&gt;");
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll("\n", "<br>");
        str = str.replaceAll("'", "&apos;");
        str = str.replaceAll("\"", "&quot;");

        return str;
    }

    public static String safeHTML2(String str){
        if (org.apache.commons.lang3.StringUtils.isEmpty(str)) {
            return "";
        }

        str = str.replaceAll("&", "&amp;");
        str = str.replaceAll(">", "&gt;");
        str = str.replaceAll("<", "&lt;");
        str = str.replaceAll("\n", "");
        str = str.replaceAll("'", "&apos;");
        str = str.replaceAll("\"", "&quot;");

        return str;
    }

    /**
     * 获取HTML内纯文本
     * @param str
     * @return
     */
    public static String stripHTML(String str){
        if (org.apache.commons.lang3.StringUtils.isEmpty(str)) {
            return "";
        }

        str = str.replaceAll("<.+?>", "");
        str = str.replaceAll("<", "");
        str = str.replaceAll(">", "");
        str = str.replaceAll("&nbsp;", "");
        return str;
    }

    public static void chartSetHint(String oldStr){
        try{
            for(String chartSetLeft : chartSetArray){
                for(String chartSetRight : chartSetArray){
                    log.info("new String(oldStr.getBytes(\""+chartSetLeft+"\"),\""+chartSetRight+"\")");
                    log.info(new String(oldStr.getBytes(chartSetLeft) , chartSetRight));
                }
                log.info("new String(oldStr.getBytes(\""+chartSetLeft+"\"))");
                log.info(new String(oldStr.getBytes(chartSetLeft)));
                log.info("new String(oldStr.getBytes(),\""+chartSetLeft+"\")");
                log.info(new String(oldStr.getBytes() , chartSetLeft));
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    public static boolean equalsAttForObject(String[] checkAtts, JSONObject obj1, JSONObject obj2){
        for(String att : checkAtts){
            if(!StringUtils.isEmpty(obj1.getString(att))
                    && (StringUtils.isEmpty(obj2.getString(att)) || !obj1.getString(att).equals(obj2.getString(att)))){
                return false;
            }
        }
        return true;
    }

    public static boolean AttForObjectisNull(String[] checkAtts, JSONObject obj1){
        for(String att : checkAtts){
            if(StringUtils.isEmpty(obj1.getString(att))){
                return false;
            }
        }
        return true;
    }
    public static String dianhoun(Double d,int n){
        StringBuffer fm = new StringBuffer();
        fm.append("##########0.");
        for(int i=0;i<n;i++){
            fm.append("0");
        }
        DecimalFormat df = new DecimalFormat(fm.toString());
        BigDecimal bg = BigDecimal.valueOf(d);
        Double j = bg.setScale(n, BigDecimal.ROUND_DOWN).doubleValue();
        return df.format(j);
    }
    public static int changeVersion(String version){
        StringBuffer versionStr = new StringBuffer();
        String[] versions = version.split("\\.");
        for(String s : versions){
            versionStr.append(StringUtils.lpad(s, 3, "0"));
        }
        return Integer.parseInt(versionStr.toString());
    }

    public static String lpad(String s, int n, String replace) {
        while (s.length() < n) {
            s = replace+s;
        }
        return s;
    }
    public static void main(String[] args) {
        chartSetHint("啊啊啊啊");
    }
}
